package com.act;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;

import com.Enum.InfoType;
import com.bean.SearchItem;
import com.bean.UserInfo;
import com.common.Constant;
import com.common.TextHttpResponseHandler;
import com.mUI.XListView;
import com.mUI.XListView.IXListViewListener;
import com.xike.kyt.R;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class RemindUserListAct extends BaseAct {

	TextView tv_back;
	EditText edt_search;
	XListView listView;
	MyUserListAdapter usersAdapter;
	int pageCursor = 1;
	boolean isRefresh = false;
	boolean isLoadingMore = false;

	HorizontalScrollView layout_chose;

	SearchItem searchResult;
	ArrayList<SearchItem.Result> users = new ArrayList<SearchItem.Result>();

	GridView gd_chose;
	MyChoseUserAdapter choseAdapter;

	ArrayList<Long> choseUserIds = new ArrayList<Long>();
	HashMap<Long, UserInfo> choseUsers = new HashMap<Long, UserInfo>();

	Bitmap defaultBitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_remind_userlist);

		BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
		defaultBitmap = MyUtil.getRoundedCornerBitmap(bd.getBitmap());
		initViews();

	}

	@Override
	protected void initViews() {
		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);

		edt_search = (EditText) findViewById(R.id.remindUsers_edt_keyword);
		edt_search.setSingleLine(true); // android:singleLine=”true”
		edt_search.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
					users.clear();
					serviceGetRemindUsers();
					return true;
				}
				return false;
			}
		});

		tv_back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		findViewById(R.id.remindUsers_tv_confirm).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (choseUserIds.size() > 0) {
					StringBuffer sb = new StringBuffer();
					for (Long id : choseUserIds) {
						sb.append(id).append(",");
					}
					String strRemindUserIds = sb.substring(0, sb.length() - 1).toString();
					Intent it = getIntent();
					it.putExtra("remindUserIds", strRemindUserIds);
					setResult(1, it);
				}
				finish();
			}
		});

		listView = (XListView) findViewById(R.id.remindUsers_listview);
		listView.setPullRefreshEnable(true);
		listView.setPullLoadEnable(true);
		listView.setAutoLoadEnable(true);

		usersAdapter = new MyUserListAdapter();
		listView.setAdapter(usersAdapter);

		listView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				pageCursor = 1;
				isRefresh = true;
				serviceGetRemindUsers();
			}

			@Override
			public void onLoadMore() {
				pageCursor++;
				isLoadingMore = true;
				serviceGetRemindUsers();
			}
		});
		layout_chose = (HorizontalScrollView) findViewById(R.id.remindUsers_layout_chose);
		layout_chose.setVisibility(View.GONE);

		gd_chose = (GridView) findViewById(R.id.remindUsers_gd_chose);
		choseAdapter = new MyChoseUserAdapter();
		gd_chose.setAdapter(choseAdapter);

	}

	@Override
	protected void updateViews() {
		ArrayList<SearchItem.Result> loadUsers = searchResult.getResults();

		if (loadUsers == null || loadUsers.size() == 0) {
			mToast.showToast(this, "暂无相关好友");
		} else {

			if (isRefresh) {
				users.clear(); // 刷新 清空
				users.addAll(loadUsers);
				usersAdapter.notifyDataSetChanged();
				listView.stopRefresh();
				listView.updateRefreshTime();
				isRefresh = false;
				listView.setPullLoadEnable(true);
			} else {
				users.addAll(loadUsers);
				usersAdapter.notifyDataSetChanged();
				if (isLoadingMore) {
					listView.stopLoadMore();
				}
				if (pageCursor * Constant.LIST_PAGESIZE < searchResult.getTotal_counts()) {
					listView.showFooterView();
				} else {
					listView.setPullLoadEnable(false);
				}
			}
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					if (choseUserIds.contains(id)) {
						choseUserIds.remove(id);
					} else {
						choseUserIds.add(id);
					}
					usersAdapter.notifyDataSetChanged();

					SearchItem.Result item = users.get(position - 1);
					UserInfo userInfo = new UserInfo();
					userInfo.setId(id);
					userInfo.setAvator(item.getUser_avator());
					userInfo.setNick_name(item.getUser_name());
					if (choseUsers.containsKey(id)) {
						choseUsers.remove(id);
					} else {
						choseUsers.put(id, userInfo);
					}
					choseAdapter.notifyDataSetChanged();

					if (choseUsers.size() > 0) {
						if (layout_chose.getVisibility() == View.GONE) {
							layout_chose.setVisibility(View.VISIBLE);
						}
					} else {
						layout_chose.setVisibility(View.GONE);
					}

				}

			});
		}
	}

	private void serviceGetRemindUsers() {

		String strKeyWord = MyUtil.getEditTextContent(edt_search);
		if (!StringUtil.isNotNull(strKeyWord)) {
			mToast.showToast(this, "是输入搜索内容");
		}
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("keyword", strKeyWord));
		params.add(new BasicNameValuePair("info_type", String.valueOf(InfoType.People.getIntValue())));
		params.add(new BasicNameValuePair("page_cursor", String.valueOf(pageCursor)));
		params.add(new BasicNameValuePair("page_count", String.valueOf(Constant.LIST_PAGESIZE)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_SEARCH, params);
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				SearchItem result = gson.fromJson(responseString, SearchItem.class);
				dealRequestResult(result);
				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(RemindUserListAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(SearchItem result) {
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				searchResult = result;
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
		}
	}

	private class MyChoseUserAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return choseUsers.size();
		}

		@Override
		public UserInfo getItem(int position) {
			return choseUsers.get(choseUserIds.get(position));
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("ViewHolder")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = View.inflate(RemindUserListAct.this, R.layout.item_remind_chose_user, null);
			ImageView img_avator = (ImageView) convertView.findViewById(R.id.item_img_remindChoseUser);

			MyUtil.displayImageView(RemindUserListAct.this, getItem(position).getAvator(), img_avator, defaultBitmap, true);
			return convertView;
		}

	}

	private class MyUserListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return users.size();
		}

		@Override
		public SearchItem.Result getItem(int position) {
			return users.get(position);
		}

		@Override
		public long getItemId(int position) {
			return getItem(position).getUser_id();
		}

		class ViewHolder {
			ImageView img_avator;
			ImageView img_chose;
			TextView tv_userName;
			TextView tv_userDesc;
		}

		ViewHolder holder;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = View.inflate(RemindUserListAct.this, R.layout.listitem_remind_user, null);
				holder.tv_userName = (TextView) convertView.findViewById(R.id.lvitem_remindUsers_tv_name);
				holder.tv_userDesc = (TextView) convertView.findViewById(R.id.lvitem_remindUsers_tv_desc);

				holder.img_chose = (ImageView) convertView.findViewById(R.id.lvitem_remindUsers_img_chose);
				holder.img_avator = (ImageView) convertView.findViewById(R.id.lvitem_remindUsers_img_avator);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			SearchItem.Result item = getItem(position);

			MyUtil.setTextViewText(holder.tv_userName, item.getUser_name(), View.GONE, "");
			MyUtil.setTextViewText(holder.tv_userDesc, item.getContent(), View.GONE, "");

			MyUtil.displayImageView(RemindUserListAct.this, item.getUser_avator(), holder.img_avator, defaultBitmap, true);

			holder.img_chose.setSelected(choseUserIds.contains(getItemId(position)));

			return convertView;

		}

	}

}
